import Axios, { AxiosError } from 'axios';
import { Notify } from 'quasar';

 //开发环境
//const baseURL = process.env.NODE_ENV === 'development'
  //? `http://${window.location.hostname === 'localhost' ? '192.168.100.2' : window.location.hostname}/uacs`
//: '/uacs';
 
const baseURL = process.env.NODE_ENV === 'development' ? '/api' : `http://${window.location.hostname}/uacs` ;  // 生产环境
export const api = Axios.create({ baseURL, timeout: 6000 });

api.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    Notify.create({ message: error.message, color: 'negative' });
    return Promise.reject(error);
  },
);

api.interceptors.response.use(
  response => {
    const status = response.data.code || 200;
    const message = response.data.message || '未知错误';
    if (status !== 200) {
      Notify.create({ message, color: 'negative' });
      return Promise.reject(new Error(message));
    }
    return response.data;
  },
  error => {
    Notify.create({ message: `数据获取失败: ${error.message}`, color: 'negative' });
    return Promise.reject(error.message);
  },
);

export const get = async <T = any>(url: string, params: Record<string, string> = {}) => {
  try {
    const { data } = await api.get<{ code: number; message: any; data: T }>(url, { params });
    return data;
  } catch (error) {
    if (error instanceof AxiosError) {
      if (error.code === 'ERR_NETWORK') {
        Notify.create({ message: '网络错误', color: 'negative' });
      } else {
        Notify.create({ message: `数据获取失败: ${error.message}`, color: 'negative' });
      }
    }
    throw error;
  }
};

export const post = async <T = any>(
  url: string,
  { data, params }: { data?: any; params?: any } = { data: null, params: null },
) => {
  try {
    const { data: res } = await api.post<{ code: number; message: string; data: T }>(url, data, { params });
    return res;
  } catch (error) {
    if (error instanceof AxiosError) {
      if (error.code === 'ERR_NETWORK') {
        Notify.create({ message: '网络错误', color: 'negative' });
      } else {
        Notify.create({ message: `数据获取失败: ${error.message}`, color: 'negative' });
      }
    }
    throw error;
  }
};
